package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.model.KnowledgeBase;
import com.zja.model.User;
import com.zja.service.Impl.KnowledgeBaseServiceImpl;
import com.zja.service.KnowledgeBaseService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author JA
 * @date: 2025/5/3
 * description:删除知识库
 */
@WebServlet("/api/knowledgebase/delete")
public class DeleteKnowledgeBaseServlet extends HttpServlet {
    private final KnowledgeBaseService knowledgeBaseService = new KnowledgeBaseServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");


        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("请先登录"));
            return;
        }

        User currentUser = (User) session.getAttribute("currentUser");

        Long id;
        try {
            id = Long.valueOf(req.getParameter("id"));
        } catch (NumberFormatException e) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("参数格式错误"));
            return;
        }

        KnowledgeBase kb = knowledgeBaseService.getById(id);
        if (kb == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("知识库不存在"));
            return;
        }

        if (!kb.getCreatorId().equals(currentUser.getId())) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("您没有权限删除该知识库"));
            return;
        }

        boolean success = knowledgeBaseService.delete(id);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("删除成功"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("删除失败"));
        }
    }
}
